import { put, takeEvery } from 'redux-saga/effects';
import axios from 'axios';
import { initListAction } from './actionCreator';

// generator 函数
function* mySaga() {
    // 接收 store.dispatch() 传过来的action
    // 接收到get_init_list的action后，会调用getInitList方法
    // getInitList可以执行异步操作
    yield takeEvery('get_init_list', getInitList);
}

function* getInitList() {
    try {
        let list = [];
        const res = yield axios.get('https://www.fastmock.site/mock/0764b93cba70add273910b232c51aad8/development/api/getHotList'); // 等待axios请求结束后，直接将结果赋值给res
        if (res.data.data.length > 0) {
            for (const val of res.data.data) {
                list.push(val.name);
            }
        }
        const action = initListAction(list);
        yield put(action); // 类似于store.dispatch(action);
    } catch (error) {
        console.log(error);
    }
}

export default mySaga;
